package net.csdn.business.webhook.config;


import net.csdn.business.common.interceptor.IRepeatSubmitConfig;
import net.csdn.business.common.interceptor.RepeatSubmitInterceptor;
import net.csdn.business.common.interceptor.impl.SameUrlDataInterceptor;
import net.csdn.business.common.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private WebHookConfigData configData;
    @Autowired
    private RedisCache redisCache;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(initRepeatSubmitInterceptor(configData)).addPathPatterns("/api/**");
    }

    @Bean("repeatSubmitInterceptor")
    public RepeatSubmitInterceptor initRepeatSubmitInterceptor(WebHookConfigData configData) {
        return new SameUrlDataInterceptor(redisCache, new RepeatSubmitConfig(configData));
    }

    private static class RepeatSubmitConfig implements IRepeatSubmitConfig {
        private final WebHookConfigData config;

        private RepeatSubmitConfig(WebHookConfigData config) {
            this.config = config;
        }

        @Override
        public String getTokenHeaderKey() {
            return config.getRepeatHeader();
        }

        @Override
        public Boolean isEnabled() {
            return config.isRepeatEnabled();
        }
    }
}